package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.consts.ErmsCodePrefix;
import com.sugon.consts.FactoryTypeEnum;
import com.sugon.dao.FactoryTypeDao;
import com.sugon.entity.FactoryTypeEntity;
import com.sugon.service.FactoryTypeService;
import com.sugon.utils.Constant;
import com.sugon.utils.MapUtil;
import com.sugon.utils.RRException;
import com.sugon.utils.ShiroUtils;
import com.sugon.utils.excel.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 设备厂家Service实现类
 *
 * @author sugon
 * @date 2020-03-06 10:13:55
 */
@Service("factoryTypeService")
public class FactoryTypeServiceImpl implements FactoryTypeService {
    @Autowired
    private FactoryTypeDao factoryTypeDao;

    @Override
    public List<FactoryTypeEntity> queryListByType(FactoryTypeEnum factoryType) {
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("type", factoryType.getValue());
        return queryList(queryParam);
    }

    /**
     * @param id 主键
     * @return
     */
    @Override
    public FactoryTypeEntity queryObject(String id) {
        return factoryTypeDao.queryObject(id);
    }

    /**
     * @param selfCode 厂家标识或自编码
     * @return
     */
    @Override
    public FactoryTypeEntity queryBySelfCode(String selfCode) {
        Map<String, Object> queryParam = new HashMap<>(1);
        queryParam.put("selfCode", selfCode);
        List<FactoryTypeEntity> factoryTypeList = queryList(queryParam);
        return CollectionUtil.isNotEmpty(factoryTypeList) ? factoryTypeList.get(0) : null;
    }

    /**
     * @param map 参数
     * @return
     */
    @Override
    public List<FactoryTypeEntity> queryList(Map<String, Object> map) {
        // 移除Map中的空值
        MapUtil.removeEmptyValue(map);
        return factoryTypeDao.queryList(map);
    }

    @Override
    public Map<String, Object> prepareExportData(Map<String, Object> map) {
        Map<String, Object> templateData = cn.hutool.core.map.MapUtil.newHashMap();
        List<FactoryTypeEntity> factoryTypeList = queryList(map);
        Map<Integer, String> factoryTyeMap = FactoryTypeEnum.toValueNameMap();
        if (CollectionUtil.isNotEmpty(factoryTypeList)) {
            int i = 1;
            for (FactoryTypeEntity factory : factoryTypeList) {
                factory.setIdx(i++);
                factory.setTypeName(factoryTyeMap.get(factory.getType()));
            }
        }
        templateData.put("list", Optional.ofNullable(factoryTypeList).orElse(CollectionUtil.newArrayList()));
        return templateData;
    }

    /**
     * 展示所有
     *
     * @return
     */
    @Override
    public Map<String, String> listAll(Integer type) {
        Map<String, String> factories = new HashMap<>();


        Map<String, Object> param = cn.hutool.core.map.MapUtil.newHashMap();
        param.put("type", type);

        List<FactoryTypeEntity> factoryTypes = queryList(param);
        for (FactoryTypeEntity factoryType : factoryTypes) {
            factories.put(factoryType.getFaName(), factoryType.getFaCode());
        }
        return factories;
    }

    /**
     * 查询数目
     *
     * @param map 参数
     * @return
     */
    @Override
    public int queryTotal(Map<String, Object> map) {
        return factoryTypeDao.queryTotal(map);
    }

    /**
     * 保存
     *
     * @param factoryType 实体
     * @return
     */
    @Override
    public int save(FactoryTypeEntity factoryType) {
        factoryType.setId(RandomUtil.randomString(32));
        // 设置厂商编码
        generateUniqueCode(factoryType);
        factoryType.setIsDel(Constant.IS_NOT_DEL_INT);
        factoryType.setCreateUser(ShiroUtils.getUserId());
        factoryType.setCreateTime(DateUtil.date());
        return factoryTypeDao.save(factoryType);
    }

    /**
     * 生成唯一码
     *
     * @param object
     * @return
     */
    @Override
    public String generateUniqueCode(Object object) {
        FactoryTypeEntity factoryTypeEntity = (FactoryTypeEntity) object;
        // 根据供应厂商类别获取编码前缀 0设备 1备件 2模具
        Integer type = factoryTypeEntity.getType();
        String faCodePrefix = null;
        switch (type) {
            case 1:
                faCodePrefix = ErmsCodePrefix.SPARE_FAC_CODE_PREFIX;
                break;
            case 2:
                faCodePrefix = ErmsCodePrefix.MOLD_FAC_CODE_PREFIX;
                break;
            default:
                faCodePrefix = ErmsCodePrefix.DEV_FAC_CODE_PREFIX;
        }
        // 只有在新增厂家或者厂家更换分类时重新生成厂家编码
        String uniqueCode = null;
        String faCode = factoryTypeEntity.getFaCode();
        if (StrUtil.isEmpty(faCode) || (StrUtil.isNotEmpty(faCode) && !faCode.startsWith(faCodePrefix))) {
            String lastestModuleCode = factoryTypeDao.getLastestFaCode(type);
            uniqueCode = com.sugon.modules.utils.StrUtil.increase(lastestModuleCode, faCodePrefix, 5, 1);
            factoryTypeEntity.setFaCode(uniqueCode);
        }
        return uniqueCode;
    }

    /**
     * 更新
     *
     * @param factoryType 实体
     * @return
     */
    @Override
    public int update(FactoryTypeEntity factoryType) {
        // 设置厂商编码
        generateUniqueCode(factoryType);
        factoryType.setUpdateUser(ShiroUtils.getUserId());
        factoryType.setUpdateTime(DateUtil.date());
        return factoryTypeDao.update(factoryType);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public int delete(String id) {
        return factoryTypeDao.delete(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(String[] ids) {
        return factoryTypeDao.deleteBatch(ids);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     */
    @Override
    public int imports(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        int num = 0;
        List<String[]> list = ExcelImport.getExcelData(file);
        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, Integer> factoryTyeMap = FactoryTypeEnum.toNameValueMap();
            for (int i = 1; i < list.size(); i++) {
                String[] array = list.get(i);
                // 供应商名称和供应商类型不能为空
                if (!StrUtil.isAllNotEmpty(array[1], array[2])) {
                    continue;
                }
                /*
                    根据厂家编码是否为空，进行保存或者更新操作
                    如果不为空，则查询现存记录
                        如果有，则更新，否则保存
                    如果为空，则执行保存
                 */
                FactoryTypeEntity factoryType = null;
                String faCode = array[4];
                if (StrUtil.isNotEmpty(faCode)) {
                    List<FactoryTypeEntity> factoryList = factoryTypeDao.queryObjectByName(faCode, 0);
                    if (CollectionUtil.isNotEmpty(factoryList)) {
                        factoryType = factoryList.get(0);
                    }
                }
                if (factoryType == null) {
                    factoryType = new FactoryTypeEntity();
                }
                factoryType.setFaName(array[1]);
                factoryType.setType(factoryTyeMap.get(array[2]));
                factoryType.setRemark(array[3]);
                if (StrUtil.isEmpty(factoryType.getId())) {
                    num += save(factoryType);
                } else {
                    num += update(factoryType);
                }
            }
        }
        return num;
    }

}
